<?php
// 应用公共文件

if ( !function_exists('recursion') ) {
    /**
     * 递归处理数组
     * @param array $array 数组
     * @param int $pid 上级id
     * @param string $parentKey 代表上级的键名
     * @param string $ownerKey 代表自己的键名
     * @param string $childKey 子集存放的键名
     * @return array
     */
    function recursion ( array $array , int $pid = 0 , $parentKey = 'pid' , $ownerKey = 'id' , $childKey = 'children' )
    {
        $data = array ();
        foreach ( $array as $k => $v ) {
            if ( $v[$parentKey] == $pid ) {
                $child = recursion($array , $v[$ownerKey] , $parentKey , $ownerKey , $childKey);
                if ( !empty($child) ) {
                    $v[$childKey] = $child;
                }
                $data[] = $v;
            }
        }
        return $data;
    }
}

if ( !function_exists('isJson') ) {
    /**
     * 检查是不是json
     * @param $value
     * @return bool
     */
    function isJson ( $value ): bool
    {
        if ( !is_string($value) || empty($value) ) {
            return false;
        }
        return is_null(json_decode($value));
    }
}

if ( !function_exists('get_file_path') ) {
    /**
     * 根据id获取文件的路径
     * @param string $id
     * @return array|string
     */
    function get_file_path ( $id = '' )
    {
        /**
         * 如果是网路连接直接原样返回
         */
        if ( is_string($id) && strpos($id , 'http') !== false ) {
            return $id;
        }

        $query = new \app\common\model\FileManager;
        if ( strpos($id , ',') !== false ) {
            $paths = $query->whereIn('id' , $id)->column('path');
            return array_map('set_file_domain' , $paths);
        }
        else {
            return set_file_domain($query->where('id' , $id)->value('path'));
        }

    }
}

if ( !function_exists('get_file') ) {
    /**
     * 根据id或获取文件信息
     * @param int $id
     * @return array
     */
    function get_file ( int $id , $field = 'id,path,name' )
    {
        $query = new \app\common\model\FileManager;
        $res   = $query->where('id' , $id)->field($field)->findOrEmpty();
        if ( $res->isEmpty() ) {
            return [];
        }

        return $res->toArray();
    }
}

if ( !function_exists('set_file_domain') ) {
    /**
     * 给文件路径拼接域名
     * @param string $path
     */
    function set_file_domain ( $path = '' )
    {
        if ( strpos($path , 'http') !== false ) {
            return $path;
        }
        $driver = config('driver.driver');
        switch ( $driver ) {
            case 'local':
                return request()->domain() . '/' . $path;
            case 'aliOss':
                return rtrim(config('upload.domain')) . '/' . $path;
            case 'qiniuOss':
                return rtrim(config('upload.domain')) . '/' . $path;
            default:
                throw new \think\Exception('不存在的存储空间');
        }
    }
}

if ( !function_exists('get_plugin_info') ) {
    /**
     * 获取插件信息
     * @param $name
     * @return mixed
     */
    function get_plugin_info ( $name )
    {
        $plugin = get_plugin_instance($name);
        return $plugin->getInfo();
    }
}

if ( !function_exists('get_plugin_instance') ) {
    /**
     * 获取插件类实例
     * @param $name
     * @return mixed|null
     */
    function get_plugin_instance ( $name )
    {
        static $_plugin = [];

        if ( isset($_plugin[$name]) ) {
            return $_plugin[$name];
        }

        $class = ( get_plugin_class($name) );
        if ( !class_exists($class) ) {
            return null;
        }
        if ( $class instanceof \app\common\plugins\Plugin ) {
            $_plugin[$name] = new $class();
        }
        else {
            $_plugin[$name] = new $class(app());
        }
        return $_plugin[$name];
    }
}

if ( !function_exists('get_plugin_class') ) {
    function get_plugin_class ( $name , $type = 'hook' , $class = null , $module = 'index' )
    {
        $name = trim($name);
        // 处理多级控制器情况
        if ( !is_null($class) && strpos($class , '.') ) {
            $class = explode('.' , $class);

            $class[count($class) - 1] = \think\helper\Str::studly(end($class));
            $class                    = implode('\\' , $class);
        }
        else {
            $class = \think\helper\Str::studly(is_null($class) ? $name : $class);
        }

        if ( $type == 'controller' ) {
            $namespace = '\\app\\plugins\\' . $name . '\\' . $module . '\\controller\\' . $class;
            if ( $module == 'index' && !class_exists($namespace) ) {
                $namespace = '\\app\\plugins\\' . $name . '\\controller\\' . $class;
            }
        }
        else {
            $namespace = '\\app\\plugins\\' . $name . '\\Plugin';
        }
        return class_exists($namespace) ? $namespace : '';
    }
}

if ( !function_exists('is_cli') ) {
    /**
     * 检测是不是cli命令行
     * @return false|int
     */
    function is_cli ()
    {
        return preg_match("/cli/i" , php_sapi_name()) ? true : false;
    }
}

if ( !function_exists('plugins') ) {
    /**
     * 获取插件实例
     * @param array $name
     * @param array $vars
     * @param false $instance
     * @return mixed
     */
    function plugins ( $name = [] , $vars = [] , $instance = false )
    {
        return \think\Container::getInstance()->make($name ?? \app\common\plugins\PluginController::class , $vars , false);
    }
}

if ( !function_exists('plugin_url') ) {
    /**
     * 插件模块url生成
     * @param string $url
     * @param array $vars
     * @return string
     */
    function plugin_url ( $url = '' , $vars = [] )
    {
        $uriMap = explode('/' , ltrim(request()->server('REQUEST_URI') , '/'));
        $uriMap = count($uriMap) < 5 ? array_pad($uriMap , 5 , 'index') : $uriMap;
        if ( !empty($url) ) {
            $urlMap    = explode('/' , $url);
            $countDiff = abs(count($uriMap) - count($urlMap));
            for ( $i = count($uriMap); $i --; $i >= 0 ) {
                if ( $i < $countDiff ) {
                    break;
                }
                $uriMap[$i] = array_pop($urlMap);
            }
        }

        $url = join('/' , $uriMap);
        if ( !empty($vars) ) {
            $query = http_build_query($vars);
            $url   .= '?' . $query;
        }
        return '/' . $url;
    }
}

if ( !function_exists('format_file_size') ) {
    function format_file_size ( int $size )
    {
        if ( '1073741824' <= $size ) {
            $file_size = round($size / 1024 / 1024 / 1024 , 2) . "GB";
        }
        elseif ( '1073741824' > $size and $size >= '1048576' ) {
            $file_size = round($size / 1024 / 1024 , 2) . "MB";
        }
        elseif ( '1048576' > $size and $size >= '1024' ) {
            $file_size = round($size / 1024 , 2) . "KB";
        }
        elseif ( '1024' > $size ) {
            $file_size = $size . "B";
        }
        return $file_size;
    }
}

if(!function_exists('default_iframe_action')){

    function default_iframe_action(){
        $module = app('http')->getName();

        if($module === 'admin'){
            return url('admin/control/control');
        }
        /**
         * @var \app\common\plugins\Plugin $plugin
         */
        $plugin = get_plugin_instance($module);
        return $plugin->getHomeAction();
    }
}
function randGoodsName ()
{
    $xingrongci = [
        '清新的' , '洁白的' , '可爱的' , '漆黑的' , '彩色的' , '宁静的' , '无语的' , '叽叽喳喳的' , '敦实的' , '消瘦的' , '结实的' , '脆弱的' , '崭新出厂的' , '战痕累累的' , '参差不齐的'
    ];

    $shiti = [
        '鞋子' , '袜子' , '外套' , 'T恤' , '裤子' , 'polo衫' , '筷子' , '碗' , '勺子' , '锅' , '盘子' , '皮带' , '车' , '轿车' , '汽车'
    ];

    return $xingrongci[rand(0 , count($xingrongci) - 1)] . $shiti[rand(0 , count($shiti) - 1)];
}

function rand_nickname ( $len )
{

    $a        = range('a' , 'z');
    $b        = range('A' , 'Z');
    $c        = range('0' , '9');
    $chars    = array_merge($a , $b , $c);
    $charslen = count($chars) - 1;
    shuffle($chars);
    $output = '';
    for ( $i = 0; $i < $len; $i ++ ) {
        $output .= $chars[mt_rand(0 , $charslen)];
    }
    return $output;
}